'''
dionysus - a web based dialogue management framework
Copyright (C) 2011  Eugeniu Costetchi <eugeniu.costetchi (at) tudor.lu>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

Created on Dec 31, 2010
'''
import re
from string import Template
import random
import string
from pprint import PrettyPrinter

def __trim_str(s, distinguish_words=True):
    if distinguish_words == False:
        return s.replace(' ', '')
    r = s.split(' ')
    l = ''
    x = []
    for i in r:
        if len(i) != 0:
            x.append(i)
    for i in range(0, len(x)):
        l += x[i] + " "
    return l[:-1]

def __trim_list(l, distinguish_words=True):
    x = []
    for i in l:
        x.append(__trim_str(i, distinguish_words))
    return x

def trim(s, distinguish_words=True):
    if type(s) == type(''):
        return __trim_str(s, distinguish_words)
    if type(s) == type([]):
        return __trim_list(s, distinguish_words)
    
def get_place_holders(string_template, only_identifiers=True):
    expr = r'\$\{[ \w ]+\}'
    x = trim(re.findall(expr, string_template), distinguish_words=False)
    
    if not only_identifiers:
        return x
    dict = []
    for i in x:
        dict.append(i[2:-1])
    return dict
    
def substitute_place_holders(string_template, place_holders):
    t = Template(string_template)
    return t.substitute(place_holders)

def iterable_to_cvs_place_holder_values(place_holdes=[], ph_pool={}):
    x = {}
    for i in place_holdes:
        if isinstance(ph_pool[i], basestring):
            x[i] = ph_pool[i]
        else:
            x[i] = ', '.join(ph_pool[i])
    return x

def random_string(length=7):
    #TODO: enforce unique random strings
    if length in range(1, 36): 
        return ''.join(random.sample(string.ascii_uppercase + string.digits, length))
    elif length < 1:
        return ''
    elif length > 36:
        return ''.join(random.sample(string.ascii_uppercase + string.digits, 36)) + random_string(length - 36)


def shrink(var, max_len=12, last=False):
    s = str(var)
    if len(s) <= max_len:
        return s
    try:
        if last:
            return '...' + s[-max_len:] 
        else:
            return s[:max_len] + '...'
    except:
        return s


def pprint(object):
    p = PrettyPrinter(indent=2, width=80, stream=str)
    return p.pformat(object)



#print pprint({'asd':'asd','sdf':'asgccvc','dd':{'123':[1,2,3,4,5,6,7,8,9,0]}})
#print iterable_to_cvs_place_holder_values(['a','b','c'], {'a':['q','v','e'],'b':('ass','qwe'), 'c':'asdgfdsghd'})

#print re.findall(r'\$\{[ \w ]+\}', 'mama ${cucu}, ${ruku}')
#print get_place_holders('mama ${cucu}, ${ruku}')

#print type('')
#print type (['',''])==type([])
#print __trim_list([' sfdfdfd dfdfd     gfgf',' dffdf','  fd fdgdhgfhgfhgh  \n '])
